package com.merelyb.util;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by LiM on 2017/12/15.
 */
public class StringCodeUtils {

    /**
     * unicode 转换字符串
     * @param sUnicode
     * @return
     */
    public static String decodeUnicode(String sUnicode) {
        Charset charset = Charset.forName("UTF-16");
        Pattern pattern = Pattern.compile("\\\\u([0-9a-fA-F]{4})");
        Matcher matcher = pattern.matcher( sUnicode );
        int iStart = 0 ;
        int iEnd = 0 ;
        StringBuffer sbString = new StringBuffer();
        while( matcher.find( iStart ) ) {
            iEnd = matcher.start() ;
            if( iEnd > iStart ){
                String sNeed = sUnicode.substring(iStart, iEnd) ;
                sbString.append( sNeed );
            }
            String code = matcher.group( 1 );
            int iData = Integer.valueOf( code , 16 );
            byte[] bData = new byte[ 4 ] ;
            bData[ 0 ] = (byte) ((iData >> 8) & 0xFF );
            bData[ 1 ] = (byte) ( iData & 0xFF ) ;
            ByteBuffer byteBuffer = ByteBuffer.wrap(bData);
            sbString.append( String.valueOf( charset.decode(byteBuffer) ).trim() );
            iStart = matcher.end() ;
        }
        iEnd = sUnicode.length() ;
        if( iEnd > iStart ){
            String seg = sUnicode.substring(iStart, iEnd) ;
            sbString.append( seg );
        }
        return sbString.toString() ;
    }
}
